/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package practica1compi1;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mario
 */
public class Principal extends javax.swing.JFrame {
    private List<clsToken> _Alfabeto= new ArrayList<clsToken>();
    private List<clsToken> myListaToken = new ArrayList<clsToken>();
    private List<clsToken> myListaTokenArbol = new ArrayList<clsToken>();
    /**
     * Creates new form Principal
     */
    public Principal() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(0, 153, 255));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setText("Analizar ER");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Mostrar AFND");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton1.setText("Mostrar Arbol");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setText("Ver Errores");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jMenu3.setText("Archivo");
        jMenuBar2.add(jMenu3);

        jMenu4.setText("Herramienta");

        jMenuItem1.setText("Crear AFN");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu4.add(jMenuItem1);

        jMenuBar2.add(jMenu4);

        setJMenuBar(jMenuBar2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(41, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton4))
                .addContainerGap(65, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
    public void WriteFile(String strT){
        
        try{
            FileWriter fw = new FileWriter("C:\\Users\\Public\\Documents\\texto.txt",false);
            PrintWriter pw =new PrintWriter(fw);
                
                pw.println(strT);
                pw.close();
            
        } catch(Exception e){
            
        }
        
    }
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:    
        
        String strT=this.jTextArea1.getText();
        this.WriteFile(strT);
        
        Practica1Gramatica parser = new Practica1Gramatica();
        parser.parser();
        
        if (parser.Result)
        {
             
            myListaToken = this.NotacionPolacaAListaTokens(parser.polaca);

            String lStrPolaca = "";

            for (int i=0;i<myListaToken.size();i++)
            {
            lStrPolaca=lStrPolaca +myListaToken.get(i)._value;
            }
            System.out.println(lStrPolaca);


            int size =this.myListaToken.size();
            for (int i=0;i<size;i++){

                if (myListaToken.get(i)._Tipo==clsToken.TipoToken.SYMBOL_ID){
                    boolean lBolExiste=false;
                    int size2=_Alfabeto.size();
                    for (int j=0;j<size2;j++)  {
                        if(_Alfabeto.get(j)._value.equals(myListaToken.get(i)._value)){
                            lBolExiste=true;
                            break;
                        }                         
                    }
                    if (!lBolExiste)    
                        _Alfabeto.add(myListaToken.get(i));
                }

            }

            

            if (_Alfabeto.size()>0)
            {
                Thompson t1 =new Thompson();
                t1.SetAlfabeto(this._Alfabeto);
                t1.Analizar(myListaToken);
                t1.DibujarMatriz();
                t1.LlenarTxtAFN();

                try {
                    String dotPath = "C:\\Program Files (x86)\\Graphviz 2.28\\bin\\dot.exe";
                    String fileInputPath = "C:\\Users\\Public\\Documents\\afn.txt";
                    String fileOutputPath = "C:\\Users\\Public\\Documents\\afn.jpg";
                    String tParam = "-Tjpg";
                    String tOParam = "-o";
                    String[] cmd = new String[5];
                    cmd[0] = dotPath;
                    cmd[1] = tParam;
                    cmd[2] = fileInputPath;
                    cmd[3] = tOParam;
                    cmd[4] = fileOutputPath;
                    Runtime rt = Runtime.getRuntime();
                    rt.exec(cmd);


                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                /*Aplica el metodo de subconjuntos*l*/
                subConjuntos c1 = new subConjuntos();
                c1.Inicilizar(t1.GetMatriz());
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
//        Thompson t2 =new Thompson();
//        t2.SetAlfabeto(this._Alfabeto);
//        t2.Analizar(myListaToken);
//        t2.LlenarTxtAFN();
//       
//        try {
//            String dotPath = "C:\\Program Files (x86)\\Graphviz 2.28\\bin\\dot.exe";
//            String fileInputPath = "C:\\Users\\Public\\Documents\\afn.txt";
//            String fileOutputPath = "C:\\Users\\Public\\Documents\\afn.jpg";
//            String tParam = "-Tjpg";
//            String tOParam = "-o";
//            String[] cmd = new String[5];
//            cmd[0] = dotPath;
//            cmd[1] = tParam;
//            cmd[2] = fileInputPath;
//            cmd[3] = tOParam;
//            cmd[4] = fileOutputPath;
//            Runtime rt = Runtime.getRuntime();
//            rt.exec(cmd);
//            
//            
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
        
        MuestraImagen m1= new MuestraImagen("C:\\Users\\Public\\Documents\\afn.jpg",this.jTextArea1.getText().toString());
        m1.setVisible(true);
        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        
        
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
       
        
        Arbol a1 = new Arbol();
        a1.Analizar(myListaToken);
        System.out.println("\n");
        System.out.println("\n");
        a1.DibujarMatriz();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        try {
            // TODO add your handling code here:

    Runtime runTime = Runtime.getRuntime(); 
    runTime.exec("rundll32 url.dll,FileProtocolHandler "+"C:\\Users\\Public\\Documents\\erores.html"); 
        } catch (IOException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton4ActionPerformed
    /**
     * Funcion para pasar un string en notaicon polaca a lista de token siguiendo 
     * el orden de la notacion polaca
     * @param pStr string en notacion polaca
     * @return Lista de token en notacion polaca        
     */
    private List<clsToken> NotacionPolacaAListaTokens(String pStr)    {
        List<clsToken> ListaTokens = new ArrayList<clsToken>();
         int f = pStr.indexOf("\"");
        pStr = pStr.replace("(", "»");
        pStr = pStr.replace(")", "»");

        String[] arrayIds = pStr.split("»");
        
        for (int i=0;i<arrayIds.length;i++){
            clsToken Token = new clsToken();
            switch(arrayIds[i])
            {
                case "*":
                Token._Tipo=clsToken.TipoToken.SYMBOL_TIMES;
                    break;
                case ".":
                  Token._Tipo=clsToken.TipoToken.SYMBOL_DOT;   
                    break;
                case "?":
                     Token._Tipo=clsToken.TipoToken.SYMBOL_QUESTION;
                    break;
                case "|":
                     Token._Tipo=clsToken.TipoToken.SYMBOL_PIPE;
                    break;
                case "+":
                     Token._Tipo=clsToken.TipoToken.SYMBOL_PLUS;
                    break;
                default:
                     Token._Tipo=clsToken.TipoToken.SYMBOL_ID;
                    break;
            }
            Token._value=arrayIds[i]; 
           if(!("").equals(arrayIds[i]))
                ListaTokens.add( Token); 
        }
        return ListaTokens;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
